package com.zero.manage.web.utils.generate.service;

import cn.hutool.core.util.StrUtil;
import com.zero.manage.web.utils.CommonUtils;
import com.zero.manage.web.utils.generate.ColumnInfo;
import com.zero.manage.web.utils.generate.DatabaseDao;
import com.zero.manage.web.utils.generate.MysqlDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Mysql数据库相关操作
 *
 * @author zero
 */
@Service
public class MysqlService implements DatabaseDao {
    @PersistenceContext
    private EntityManager entityManager;
    @Autowired
    private MysqlDao mysqlDao;

    @Override
    public List<String> getCatalogs() {
        return mysqlDao.getCatalogs();
    }

    @Override
    public List<Map<Object, Object>> getTableInfo(String catalogs) {
        return mysqlDao.getTableInfo(catalogs);
    }

    @Override
    public List<ColumnInfo> getColumns(String catalogs, String tableName) {
        List<Object[]> resultList = entityManager.createNativeQuery(
                String.format("show full fields from %s.%s", catalogs, tableName)
        ).getResultList();
        List<ColumnInfo> list = new ArrayList<>();
        for (Object[] objArr : resultList) {
            ColumnInfo build = ColumnInfo.builder()
                    .columnName(objArr[0].toString())
                    .remarks(CommonUtils.handleObjTurnStr(objArr[8]))
                    .typeName(StrUtil.subBefore(objArr[1].toString(), "(", false))
                    .isPrimaryKey(Objects.equals("PRI", CommonUtils.handleObjTurnStr(objArr[4])))
                    .build();
            list.add(build);
        }
        return list;
    }
}
